const util = {
  formatTime: date => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(util.formatNumber).join('/') +
      ' ' + [hour, minute, second].map(util.formatNumber).join(':');
  },

  formatNumber: n => {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },

  formatHtml: content => {
    if (!content) {
      return;
    }
    content = content.replace(/<p/gi,
      '<p style="max-width:100% !important;word-wrap:break-word;word-break:break-word;" ');
    content = content.replace(/<image/gi,
      '<image style="max-width:100% !important;height:auto !important;margin:0;display:flex;" ');
    content = content.replace(/style="/gi,
      'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break:break-word;');
    content = content.replace(/<table/gi,
      '<table style="table-layout:fixed;word-wrap:break-word;word-break:break-word;" ');
    content = content.replace(/<td/gi,
      '<td cellspacing="0" cellpadding="0" style="border-width:1px; border-style:solid; border-color:#666; margin: 0px; padding: 0px;"'
    );
    content = content.replace(/width=/gi, 'sss=');
    content = content.replace(/height=/gi, 'sss=');
    content = content.replace(/\/>/gi,
      ' style="max-width:100% !important;height:auto !important;margin:0;display:block;" />');
    return content;
  },

  /**
   * 移除购物车Tabbar的数字
   */
  removeTabBadge: () => {
    // uni.removeTabBarBadge({
    //   index: 3
    // });
  },
  /**
   * 获取链接上的参数
   */
  getUrlKey: (name) => {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || ['',
      ''
    ])[1].replace(/\+/g, '%20')) || null;
  },
  /**
   * 文件地址校验
   * @param fileUrl 获取到的文件路径
   */
  checkFileUrl: (fileUrl) => {
    // 防止 fileUrl 为null时 indexOf() 方法失效报错
    const url = fileUrl || '';
    const baseUrl = import.meta.env.VITE_APP_RESOURCES_URL;
    // 判断 fileUrl 中是否已存在基础路径
    const check = url.indexOf(baseUrl) !== -1;
    if (check || !fileUrl) {
      return url;
    } else {
      return baseUrl + url;
    }
  },
  /**
   * 图片地址校验
   * @param imageUrl 获取到的图片路径
   */
  checkImageUrl: (imageUrl) => {
    console.log(imageUrl);
    if (util.judgeNull(imageUrl)) {
      return null;
    }
    // 防止 imageUrl 为null时 indexOf() 方法失效报错
    const url = imageUrl || '';
    const baseUrl = import.meta.env.VITE_APP_RESOURCES_URL;
    // 判断 imageUrl 中是否已存在基础路径
    const check = url.indexOf('http') !== -1 || url.indexOf('https') !== -1 || url.indexOf(baseUrl) !== -1;
    if (imageUrl.indexOf('/admin') > 0) {
      return baseUrl + url;
    } else if (check) {
      return url;
    } else {
      return baseUrl + url;
    }
  },

  getLoginCode: () => {
    return new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: loginRes => {
          console.log('loginRes', loginRes, loginRes.code);
          resolve(loginRes);
        }
      })
    })
  },
  getUserProfile: () => {
    return new Promise((resolve, reject) => {
      uni.getUserProfile({
        desc: '获取您的微信信息以授权小程序',
        success: userRes => {
          console.log('getUserProfile-res', userRes);
          resolve(userRes);
        },
        fail: userErr => {
          tip.toast('授权失败', 1000, 'error');
          console.log('getUserProfile-err', userErr);
          reject(userErr);
        }
      })
    })
  },
  getUserInfo: () => {
    return new Promise((resolve, reject) => {
      uni.getUserInfo({
        provider: 'weixin',
        withCredentials: true,
        lang: 'zh_CN',
        success: userRes => {
          console.log('getUserInfo-res', userRes);
          resolve(userRes);
        },
        fail: userErr => {
          tip.toast('授权失败', 1000, 'error');
          console.log('getUserInfo-err', userErr);
          reject(userErr);
        }
      })
    })
  },
  judgeNull: (val) => {
    return val === undefined || val === null || (val === '' && val.length === 0) || JSON.stringify(val) === '{}';
  },
  // 32位随机数
  randomString: (length) => {
    let str = 'ABCDEFGHIJKIMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let randomStr = '';
    for (let i = 0; i < length; i++) {
      randomStr += str.charAt(Math.floor(Math.random() * str.length));
    }
    return randomStr;
  },
  // 小程序分享进入或二维码进入封装方法
  sharedParameterAnalysis: (options) => {
    // 小程序分享跳转处理
    if (options?.share) {
      console.log("小程序分享，路径中的参数 ==》 ", options);
      // uni.setStorageSync('venId', venId.value);

      // 小程序分享跳转处理
      // uni.navigateTo({
      //   url: "/" + options.path + "?" + options.query,
      // });
    } else if (options?.q) { //直接看这个！！！！！！！！！！！！！！！！！！！！！！
      // 小程序自动加密，需要解码
      const url = decodeURIComponent(options.q);
      const regex = /[?&]([^=#]+)=([^&#]*)/g;
      const params = {};
      let match;
      while ((match = regex.exec(url))) {
        params[match[1]] = match[2];
      }
      console.log("二维码分享，路径中的参数 ==》 ", params);

      if (!util.judgeNull(params.path)) {
        // 小程序分享跳转处理
        // uni.navigateTo({
        //   url: "/" + params.path + "?" + params.query,
        // });
      }
    } else {
      // 未知参数
      console.log("未知参数");
      tip.toast('未知参数');
    }
  },
  transPayStatus: (payStatus) => {
    let transAfterPayStatus = '';
    switch (payStatus) {
      case '待支付':
        transAfterPayStatus = 'B';
        break;
      case '已支付':
        transAfterPayStatus = 'C';
        break;
      case '已退款':
        transAfterPayStatus = 'D';
        break;
      default:
        transAfterPayStatus = '';
        break;
    }
    // if (util.judgeNull(transAfterPayStatus)) {
    //   tip.toast('订单状态转换失败');
    // }
    return transAfterPayStatus;
  },
  deepClone: (obj, hash = new WeakMap()) => {
    if (obj === null || typeof obj !== 'object') {
      // 基本类型直接返回
      return obj;
    }
    if (hash.has(obj)) {
      // 循环引用的处理
      return hash.get(obj);
    }
    let cloneObj = new obj.constructor();
    hash.set(obj, cloneObj);
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        cloneObj[key] = util.deepClone(obj[key], hash);
      }
    }
    return cloneObj;
  },

  spliceDate: (dateStr) => {
    if (!dateStr) return;
    return dateStr.split(' ')[0];
  },

  // 转换为价格的格式
  toPrice: (val) => {
    if (!val) {
      val = 0;
    }
    val = Number(val);
    return val.toFixed(2);
  },
  // 价格展示
  parsePrice: (val) => {
    if (!val) {
      val = 0;
    }
    return val.toFixed(2).split('.');
  },

  // 处理数字，用于计算
  toNum: (rectifyNum, How) => {
    if (!rectifyNum || isNaN(Number(rectifyNum))) {
      return 0;
    }
    let number = Number(rectifyNum);
    let num;
    let how = !How || isNaN(Number(How)) ? 0 : Number(How);
    if (number >= 0) {
      num = Math.round(number * Math.pow(10, how)) / Math.pow(10, how);
    } else {
      let num_1 = Math.abs(number);
      let num_11 = Math.round(num_1 * Math.pow(10, how)) / Math.pow(10, how);
      num = -num_11;
    }
    return num;
  },
  // 处理数字，用于展示
  showNum: (rectifyNum, How) => {
    let how = !How || isNaN(Number(How)) ? 0 : Number(How);
    let numStr = how > 0 ? '0.' : '0';
    if (!rectifyNum || isNaN(Number(rectifyNum))) {
      for (let i = 0; i < how; i++) {
        numStr += '0';
      }
      return numStr;
    }
    let number = Number(rectifyNum);
    let num;
    if (number >= 0) {
      num = Math.round(number * Math.pow(10, how)) / Math.pow(10, how);
    } else {
      let num_1 = Math.abs(number);
      let num_11 = Math.round(num_1 * Math.pow(10, how)) / Math.pow(10, how);
      num = -num_11;
    }

    numStr = num.toString();
    let retStr = numStr.indexOf('.');
    if (retStr < 0 && how > 0) {
      retStr = numStr.length;
      numStr += '.';
    }
    while (numStr.length <= retStr + how) {
      numStr += '0';
    }
    return numStr;
  },

  // 取整
  rounding: (val) => {
    if (!val) {
      val = 0;
    }
    return parseInt(val);
  },
}

export default util
